package com.yunxin.download.server.infra.utils;

import cn.hutool.core.text.CharSequenceUtil;
import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import com.yunxin.download.server.infra.support.file.FileHeader;
import com.yunxin.download.server.infra.support.file.FileHeaderItem;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @author zero°
 * @since 2023-06-15
 */

public enum FileHeaderUtils {

    /**
     * 实例
     */
    X;

    /**
     * 获取表头
     *
     * @return
     */
    public List<FileHeaderItem> getFilelHeader(Class<? extends FileHeader> excelHeaderClass) {
        Field[] declaredFields = excelHeaderClass.getDeclaredFields();
        List<FileHeaderItem> excelHeaderItems = new ArrayList<>();
        for (Field declaredField : declaredFields) {
            String name = declaredField.getName();
            ExcelProperty excelPropertyAnnotation = declaredField.getAnnotation(ExcelProperty.class);
            ExcelIgnore excelIgnore = declaredField.getAnnotation(ExcelIgnore.class);
            if (excelPropertyAnnotation != null) {
                //只拿第一个值
                String[] value = excelPropertyAnnotation.value();
                int index = excelPropertyAnnotation.index();
                if (value != null && CharSequenceUtil.isNotBlank(value[0]) && excelIgnore == null) {
                    FileHeaderItem excelHeaderItem = FileHeaderItem
                            .builder()
                            .excelColumnName(value[0])
                            .propName(name)
                            .index(index)
                            .build();
                    excelHeaderItems.add(excelHeaderItem);
                }

            }
        }
        if (!excelHeaderItems.isEmpty()) {
            //重新排序
            Collections.sort(excelHeaderItems, Comparator.comparingInt(FileHeaderItem::getIndex));
        }
        return excelHeaderItems;
    }


}
